package com.agileai.esb.smc.controller.common;

import java.util.ArrayList;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.sysres.SkAppManage;
import com.agileai.esb.smc.common.TreeBuilder;
import com.agileai.esb.smc.common.TreeBuilder.Node;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

public class ContentProviderHandler extends BaseHandler {
	@PageAction
	public ViewRenderer prepareDisplay(DataParam param) {
		List<TreeBuilder.Node> nodes = new ArrayList<TreeBuilder.Node>();
		SkAppManage skAppManage = this.lookupService(SkAppManage.class);
		List<DataRow> records = skAppManage.findTreeRecords(param.getString("userId"));
		String serverName = this.dispatchServlet.getServletContext().getInitParameter("serverName");
		
		for (int i = 0; i < records.size(); i++) {
			DataRow dataRow = records.get(i);
			String funcId = dataRow.stringValue("FUNC_ID");
			if (TreeBuilder.ROOT_ID.equals(funcId)){
				continue;
			}
			Node node = new Node();
			node.setId(funcId);
			node.setPid(dataRow.stringValue("FUNC_PID"));
			node.setText(dataRow.stringValue("FUNC_NAME"));
			String funcURL = dataRow.stringValue("FUNC_URL");
			if (funcURL.startsWith("index?")){
				funcURL = serverName + "/SMC/casindex"+funcURL.substring(5);
			}
			node.setUrl(funcURL);
			nodes.add(node);
		}

		TreeBuilder treeBuilder = new TreeBuilder(nodes);
		try {
			this.setAttribute("datas", treeBuilder.buildJSONTree());			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new LocalRenderer(getPage());
	}
}
